#!/usr/bin/env python
# -*- coding:utf-8 -*-
import base64

from controller.verifyCodeController import VerifyCodeController
from models import db
from utils.captcha.captcha import captcha
from utils.loggings import loggings
from utils.response_code import RET, error_map_EN


class VerifyCodeService(VerifyCodeController):
    @classmethod
    def create_verify_code(cls):
        try:
            # 生成图片验证码
            name, text, image_data = captcha.generate_captcha()

            # 准备验证码的数据
            verify_code = {
                "verify_code": text
            }
            res = cls.add(**verify_code)

            if res['code'] != RET.OK:
                return {'code': RET.DBERR, 'message': '数据库异常，生成验证码失败', 'data': res['data']}

            result = {
                'verify_code_id': str(res['data'].get('verify_code_id')),
                'verify_code': text,
                'verify_code_base64': 'data:image/jpg;base64,{0}'.format(
                    str(base64.encodebytes(image_data))[2:-1].replace("\\n", "")),
            }

            # 返回图片
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': result}

        except Exception as e:
            # 错误信息记录日志
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': '数据库异常，生成验证码失败', 'data': {'error': str(e)}}

    @classmethod
    def check_verify_code(cls, verify_code_id, verify_code):
        """
        校验验证码
        :param verify_code_id: 验证码ID
        :param verify_code: 验证码
        :return:
        """
        try:
            filter_list = []
            filter_list.append(cls.verify_code_id == verify_code_id)
            filter_list.append(cls.is_deleted == 0)
            verify_code_model = db.session.query(cls).filter(*filter_list)
            verify_code_object = verify_code_model.first()

            # 从数据库拿到验证码的值以后就删除
            verify_code_model.update({
                'is_deleted': 1
            })
            db.session.commit()

            # 如果为空，验证码过期
            if not verify_code_object:
                return {'code': RET.DATAERR, 'message': '验证码不正确', 'error': '验证码不正确'}

            # 检查验证码时间有效性
            # verify_code_time = datetime.datetime.strptime(str(verify_code_object.CreateTime), "%Y-%m-%d %H:%M:%S")
            # now_time = datetime.datetime.now()

            # if (now_time - verify_code_time).seconds > Settings.IMAGE_CODE_REDIS_EXPIRES:
            #     return {'code': RET.DATAERR, 'message': '验证码已过期', 'error': '验证码已过期'}

            # 检查验证码正确性
            if verify_code_object.verify_code != verify_code.upper():
                return {'code': RET.DATAERR, 'message': '验证码不正确', 'error': '验证码不正确'}

            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': verify_code_object.verify_code}

        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DATAERR, 'message': '数据库异常，校验验证码失败', 'error': '数据库异常，校验验证码失败'}
